package com.sziit.se.highconcurrency.common.tool;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.sziit.se.highconcurrency.common.constant.HttpResponseCodeEnums;
import com.sziit.se.highconcurrency.common.constant.SystemConstants;
import com.sziit.se.highconcurrency.common.exception.CustomException;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {

    public static final int MINUTE = 60 * 1000;
    /**
     * 过期时间
     */
    public static final int EXPIRE_TIME = 60 * MINUTE * 24;
    public static final String CLAIM_KEY_USERID = "userId";

    public static final String CLAIM_KEY_USERNAME = "userName";

    public static final String CLAIM_KEY_ROLE = "role";

    private static final String SECRET = "Token-SECRET-EMALL";

    private JwtUtils() {
    }

    /**
     * 生成签名
     *
     * @param userId   用户名
     * @param userName 用户的密码
     * @return 加密的token
     */
    public static String sign(String userName, String userId, String role) {
        //token 过期时间为24小时
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);

        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        // 附带userId和UserName信息
        return JWT.create().withClaim(CLAIM_KEY_USERNAME, userName).withClaim(CLAIM_KEY_USERID, userId).withClaim(CLAIM_KEY_ROLE, role).withExpiresAt(date).sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     *
     * @return 是否正确
     */
    public static boolean verify(String token, String userId) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withClaim(CLAIM_KEY_USERID, userId).build();
            // 效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(CLAIM_KEY_USERID).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUserName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(CLAIM_KEY_USERNAME).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    public static String getUserRole(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(CLAIM_KEY_ROLE).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    /**
     * 根据request中的token获取用户账号
     */
    public static String getUserId(HttpServletRequest request) {
        String accessToken = request.getHeader(SystemConstants.TOKEN_HEADER);
        String account = getUserId(accessToken);
        if (StrUtil.isEmpty(account)) {
            throw new CustomException(HttpResponseCodeEnums.UNAUTHORIZED.getCode(), "token解析失败");
        }
        return account;
    }

}
